package com.distributor;

 

 
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class PinDialog extends Dialog implements android.view.View.OnClickListener
{
	RelativeLayout mainLayout;
	LinearLayout layout_authenticate,layout_newPin;
	EditText etCurrentPin,etNewPin,etConfirmPin;
	Button btnOk,btnCancel;
	private ProgressDialog pd=null;
	Handler handler=new Handler();
	Context mContext;
	MD5Generator mD5Generator=new MD5Generator();
	HttpConn httpConn=new HttpConn();
	boolean isValidUser=false;
	
	public PinDialog(Context context)
	{
		super(context);
		mContext=context;
		requestWindowFeature(Window.FEATURE_NO_TITLE) ;
		setContentView(com.distributor.R.layout.change_pin);
		mainLayout=(RelativeLayout)findViewById(R.id.dialog_topup_root);
		layout_authenticate=(LinearLayout)findViewById(R.id.layout_authenticate);
		layout_newPin=(LinearLayout)findViewById(R.id.layout_newPin);
		etCurrentPin=(EditText)findViewById(R.id.etCurrentPin);
		 
		btnOk=(Button)findViewById(R.id.btn_ok);
		btnCancel=(Button)findViewById(R.id.btn_Cancel);
		
		btnOk.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
	}

	public void onClick(View v) 
	{
		if (v == btnOk)
		{
	    	 if(etCurrentPin.getText().toString().equals(""))
                Toast.makeText(mContext,"Enter Current Pin",Toast.LENGTH_LONG).show();
	    	 else
	    	 {
	    		 if(!isValidUser)
	    		 {
	    			 //authenticate use first
		    		 pd=ProgressDialog.show(mContext,    
							 null,"Please Wait..." , true);
		    		 pd.setContentView(R.layout.progress);
		    		 new Thread(authenticateUser,"Authenticat_User").start();
	    		 }
	    		 else
	    		 {
	    			 //requesting for new pin
	    			 pd=ProgressDialog.show(mContext,    
							 null,"Please Wait..." , true);
	    			 pd.setContentView(R.layout.progress);
	    			 new Thread(ChangePin,"Change_pin").start();
	    		 }
	    	 } 
             
		}
	    else if(v==btnCancel)
		{
			dismiss();
		}
		
	}
	Runnable ChangePin=new Runnable()
	{
		
		public void run() 
		{
			try
			{
				etNewPin=(EditText)findViewById(R.id.etNewPin);
				etConfirmPin=(EditText)findViewById(R.id.etConfirmPin);
				
//				 String newPass=etNewPin.getText();
//                 String confimPass=etConfirmPin.getText();
				
				if(etNewPin.getText().toString().equals("")||
						etConfirmPin.getText().toString().equals(""))
				{
					handler.post(new Runnable() 
					{
						public void run() 
						{
							pd.dismiss();
							Toast.makeText(mContext, "Enter pin",Toast.LENGTH_SHORT).show();
						}
					});
				}
				else if(!etNewPin.getText().toString().equals(etConfirmPin.getText().toString()))
				{
					handler.post(new Runnable() 
					{
						public void run() 
						{
							pd.dismiss();
							System.out.println("new Pin:"+etNewPin.getText());
							System.out.println("Confirm pin:"+etConfirmPin.getText());
							Toast.makeText(mContext, "Pin not matching",Toast.LENGTH_SHORT).show();
						}
					});
				} 
				else if(!(etNewPin.getText().length()==6))
				{
					handler.post(new Runnable() 
					{
						public void run() 
						{
							pd.dismiss();
							Toast.makeText(mContext, "PIN must be of 6 digit.",Toast.LENGTH_SHORT).show();
						}
					});
				}
				else
				{
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(AppData.hostURL+"/WebService/iTopUp/distributorapp.php");
					
					 UserInfo userInfo=AppData.getUserInfo();
                     String checksum=mD5Generator.MD5(mD5Generator.SHA1(userInfo.getLoginID()+"|"+etNewPin.getText().toString()+"|"+userInfo.getTransactionPassword()+"|"+userInfo.getpublickey()));
                     System.out.println("Check Sum String:"+checksum);
                     System.out.println("Check Sum:"+checksum);
                     
                     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                     
				        nameValuePairs.add(new BasicNameValuePair("function", "MobileChangePassword"));
				        nameValuePairs.add(new BasicNameValuePair("LoginId", userInfo.getLoginID()));
				        nameValuePairs.add(new BasicNameValuePair("MobilePassword", etNewPin.getText().toString()));
				        nameValuePairs.add(new BasicNameValuePair("TransactionPassword",userInfo.getTransactionPassword()));
				        nameValuePairs.add(new BasicNameValuePair("Checksum",checksum));
				        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				        ResponseHandler<String> responseHandler = new BasicResponseHandler();
				        String response = httpclient.execute(httppost,responseHandler);
				        System.out.println("Response:"+response);
				        
				        final JSONObject jsonObject=new JSONObject(response);
                        if(jsonObject.getString("ResponseCode").equals("000"))
                        {
                        	 handler.post(new Runnable() 
                        	 {
								public void run() 
								{
									pd.dismiss();
									dismiss();
									Toast.makeText(mContext, "Pin changed Successfully",Toast.LENGTH_SHORT).show();
								 }
							});
                        }
                        else
                        {
                        	handler.post(new Runnable() 
	                       	 {
									public void run() 
									{
										pd.dismiss();
										dismiss();
										try {
											Toast.makeText(mContext, jsonObject.getString("ResponseDescription"),Toast.LENGTH_SHORT).show();
										} catch (JSONException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								});
                        }
				}
				
				
			}
			catch(final Exception e)
			{
				pd.dismiss();
				handler.post(new Runnable() 
              	 {
						public void run() 
						{
							pd.dismiss();
							dismiss();
							Toast.makeText(mContext,""+e.getMessage() ,Toast.LENGTH_SHORT).show();
						}
				 });
				e.printStackTrace();
			}
			
		}
	};
	
	Runnable authenticateUser=new Runnable()
	{
		
		public void run() 
		{
			try
			{
				String userId=AppData.imei;
				String checksum=mD5Generator.MD5(mD5Generator.SHA1((userId+"|"+etCurrentPin.getText().toString())));
	            System.out.println("Check Sum:"+checksum);
	            String url=AppData.hostURL+"/WebService/iTopUp/distributorapp.php/MobileAuthentication/LoginUsername/"+userId+"/LoginPassword/"+etCurrentPin.getText().toString()+"/Checksum/"+checksum+"/format/json";
	            System.out.println("URL==>"+url);
	            String result=httpConn.createHttpConn(url);
	            System.out.println("Response:"+result);
	            if(result==null)
				{
					handler.post( new Runnable() 
					{ 
						public void run() 
						{
						 	pd.dismiss();
							 
							Toast.makeText(mContext,mContext.getString(R.string.conn_msg), Toast.LENGTH_SHORT).show();
						}
						
					});
					
				}
	            else
	            {
	            	JSONObject jsonObject=new JSONObject(result); 
					String responseCode=jsonObject.getString("ResponseCode");
					final String responseDesc=jsonObject.getString("ResponseDescription");
					
					if(responseCode.equals("000")&& responseDesc.equals("Successfull"))
					{
						System.out.println("Checking Successful");
						handler.post(new Runnable() 
						{
							public void run() 
							{
								isValidUser=true;
								pd.dismiss();
								dismiss();
								RelativeLayout ll=(RelativeLayout)findViewById(R.id.dialog_topup_root);
								ViewGroup.LayoutParams params=ll.getLayoutParams();
								params.height=params.height+80;
								ll.setLayoutParams(params);
								layout_authenticate.setVisibility(LinearLayout.GONE);
								layout_newPin.setVisibility(LinearLayout.VISIBLE);
								
								show();
								//Toast.makeText(mContext,"Pin is valid", Toast.LENGTH_SHORT).show();
						 	}	
						});
					}
					else
					{
						handler.post(new Runnable() 
						{
							public void run() 
							{
								pd.dismiss();
								
								Toast.makeText(mContext,"Invalid Pin", Toast.LENGTH_SHORT).show();
						 	}	
						});
					}
	            }
	            
			}
			catch(final Exception e)
			{
				pd.dismiss();
				handler.post(new Runnable() 
              	{
					public void run() 
					{
						pd.dismiss();
						dismiss();
						Toast.makeText(mContext,""+e.getMessage() ,Toast.LENGTH_SHORT).show();
					}
              	});
				e.printStackTrace();
			}
		}
	};
}
